package com.jy.app.lib.view.uilistview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.jy.app.lib.R;
import com.jy.app.lib.utils.DensityUtil;
import com.jy.app.lib.utils.LogUtil;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;


public class UIListView extends ListView implements OnScrollListener {
    private Context context;
    private boolean enableHeader = true;
    private boolean enableFooter = true;
    private boolean enableFooter_AutoLoad = true;
    private volatile boolean isXmoving = false;

    public void setEnableHeader(boolean enable) {
        this.enableHeader = enable;
    }

    public void setEnableFooter(boolean enable) {
        this.enableFooter = enable;
        if (enable) {
            if (mFooterView != null) {
                removeFooterView(mFooterView);
                mFooterView = null;
            }
            mFooterView = new UIListViewFooter(context);
            addFooterView(mFooterView);
        } else {
            if (mFooterView != null) {
                removeFooterView(mFooterView);
                mFooterView = null;
            }
        }
        setPullLoadEnable(enableFooter);
        this.setFooterDividersEnabled(enable);

    }

    public void setEnableFooterAutoLoad(boolean enable) {
        this.enableFooter_AutoLoad = enable;
    }

    private float mLastY = -1; // save event y
    private Scroller mScroller; // used for scroll back
    private OnScrollListener mScrollListener; // user's scroll listener

    // the interface to trigger refresh and load more.
    private ICListViewListener mListViewListener;

    // -- header view
    private UIListViewHeader mHeaderView;
    // header view content, use it to calculate the Header's height. And hide it
    // when disable pull refresh.
    private RelativeLayout mHeaderViewContent;

    private int mHeaderViewHeight; // header view's height
    private boolean mEnablePullRefresh = true;
    private boolean mPullRefreshing = false; // is refreashing.

    // -- footer view
    private UIListViewFooter mFooterView;
    private boolean mPullLoading;
    private boolean mIsFooterReady = false;
    private boolean mIsPullLoadCompleted = false;
    // total list items, used to detect is at the bottom of listview.
    private int mTotalItemCount;

    // for mScroller, scroll back from header or footer.
    private int mScrollBack;
    private final static int SCROLLBACK_HEADER = 2;
    private final static int SCROLLBACK_FOOTER = 1;

    private final static int SCROLL_DURATION = 300; // scroll back duration
    private final static int PULL_LOAD_MORE_DIP_DELTA = 15;// ��ݲ�ͬ�ܶ�PULL_LOAD_MORE_DELTA
    private static int PULL_LOAD_MORE_DELTA = 40; // when pull up >= 50px
    // at bottom, trigger
    // load more.
    private final static float OFFSET_RADIO = 1.8f; // support iOS like pull
    // feature.

    /**
     * @param context
     */
    public UIListView(Context context) {
        super(context);
        initWithContext(context);
    }

    public UIListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getAttr(context, attrs);
        initWithContext(context);
    }

    public UIListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        getAttr(context, attrs);
        initWithContext(context);
    }

    private void getAttr(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs,
                R.styleable.clist_attr);
        enableHeader = ta
                .getBoolean(R.styleable.clist_attr_enableHeader, false);
        enableFooter = ta
                .getBoolean(R.styleable.clist_attr_enableFooter, false);
        enableFooter_AutoLoad = ta.getBoolean(
                R.styleable.clist_attr_enableFooter_AutoLoad, false);
        ta.recycle();
    }

    private void initWithContext(Context context) {
        this.context = context;
        mScroller = new Scroller(context, new DecelerateInterpolator());
        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
        // XListView need the scroll event, and it will dispatch the event to
        // user's listener (as a proxy).
        super.setOnScrollListener(this);
        PULL_LOAD_MORE_DELTA = DensityUtil.dip2px(context, PULL_LOAD_MORE_DIP_DELTA);
        // init header view
        mHeaderView = new UIListViewHeader(context);
        mHeaderViewContent = (RelativeLayout) mHeaderView
                .findViewById(R.id.xlistview_header_content);

        addHeaderView(mHeaderView);
        // init header height
        mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        mHeaderViewHeight = mHeaderViewContent.getHeight();
                        getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                    }
                });
        setPullRefreshEnable(enableHeader);

        // init footer view
        setEnableFooter(enableFooter);
        // this.setFooterDividersEnabled(false);
    }

    private void setPullRefreshEnable(boolean enable) {
        mEnablePullRefresh = enable;
        if (!mEnablePullRefresh) { // disable, hide the content
            mHeaderViewContent.setVisibility(View.INVISIBLE);
        } else {
            mHeaderViewContent.setVisibility(View.VISIBLE);
        }
    }

    private void setPullLoadEnable(boolean enable) {
        enableFooter = enable;
        if (!enableFooter) {
            if (mFooterView != null) {
                mFooterView.hide();
                mFooterView.setOnClickListener(null);
            }

        } else {
            mPullLoading = false;

            if (mFooterView != null) {
                mFooterView.show();
                mFooterView.setState(UIListViewFooter.STATE_NORMAL);
                // both "pull up" and "click" will invoke load more.
                mFooterView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startLoadMore();
                    }
                });
            }
        }
    }

    public void stopRefresh() {
//        LogUtil.i("-------------------------------------------------stopRefresh-setComplete,mPullRefreshing="+mPullRefreshing);
        if (mPullRefreshing == true) {
            mPullRefreshing = false;
            mHeaderView.setComplete();
        }
        postDelayed(new Runnable() {
            @Override
            public void run() {
            resetHeaderHeight();
            }
        },700);
    }

    public void stopRefreshError() {
//        LogUtil.i("-------------------------------------------------stopRefresh-setComplete,mPullRefreshing="+mPullRefreshing);
        if (mPullRefreshing == true) {
            mPullRefreshing = false;
            mHeaderView.setError();
        }
        postDelayed(new Runnable() {
            @Override
            public void run() {
                resetHeaderHeight();
            }
        },700);
    }

    public void stopLoadMore() {
        if (mPullLoading == true) {
            mPullLoading = false;
        }
        mIsPullLoadCompleted = false;
        if (mFooterView != null) {
            mFooterView.setState(UIListViewFooter.STATE_NORMAL);
        }

    }

    public void LoadCompleted() {
        mIsPullLoadCompleted = true;
        if (mFooterView != null) {
            mFooterView.setState(UIListViewFooter.STATE_COMPLETE);
        }
    }

    private void invokeOnScrolling() {
        if (mScrollListener instanceof OnCScrollListener) {
            OnCScrollListener l = (OnCScrollListener) mScrollListener;
            l.onXScrolling(this);
        }
    }

    private void updateHeaderHeight(float delta) {
        int dynamycHeaderHeight = (int) delta + mHeaderView.getVisiableHeight();
        LogUtil.i("dynamycHeaderHeight="+dynamycHeaderHeight+",VisiableHeight="+mHeaderView.getVisiableHeight()+",headerHeight="+mHeaderViewHeight+",%"+accuracy(mHeaderView.getVisiableHeight(),mHeaderViewHeight,0));
        int pro = accuracy(mHeaderView.getVisiableHeight(),mHeaderViewHeight,0);
        mHeaderView.setVisiableHeight(dynamycHeaderHeight,pro);
        if (mEnablePullRefresh && !mPullRefreshing) {
            if (mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
                mHeaderView.setState(UIListViewHeader.STATE_READY);
            } else {
                mHeaderView.setState(UIListViewHeader.STATE_NORMAL);
            }
        }
        setSelection(0); // scroll to top each time
    }

    /**
     * reset header view's height.
     */
    private void resetHeaderHeight() {
        int height = mHeaderView.getVisiableHeight();
        if (height == 0) // not visible.
            return;
        // refreshing and header isn't shown fully. do nothing.
        if (mPullRefreshing && height <= mHeaderViewHeight) {
            return;
        }
        int finalHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mPullRefreshing && height > mHeaderViewHeight) {
            finalHeight = mHeaderViewHeight;
        }
        mScrollBack = SCROLLBACK_HEADER;
        //下拉的HeaderView复位的时候这边调用
        mScroller.startScroll(0, height, 0, finalHeight - height,
                SCROLL_DURATION);
        // trigger computeScroll
        invalidate();
    }

    private void updateFooterHeight(float delta) {
        if (mFooterView == null) return;
        int height = mFooterView.getBottomMargin() + (int) delta;
        if (enableFooter && !mPullLoading) {
            if (height > PULL_LOAD_MORE_DELTA) { // height enough to invoke load
                // more.
                mFooterView.setState(UIListViewFooter.STATE_READY);
            } else {
                if (mIsPullLoadCompleted) {
                    mFooterView.setState(UIListViewFooter.STATE_COMPLETE);
                } else {
                    mFooterView.setState(UIListViewFooter.STATE_NORMAL);
                }

            }
        }
        mFooterView.setBottomMargin(height);
        resetFooterHeight();

        // setSelection(mTotalItemCount - 1); // scroll to bottom
    }

    private void resetFooterHeight() {
        if (mFooterView == null) return;
        int bottomMargin = mFooterView.getBottomMargin();
        if (bottomMargin > 0) {
            mScrollBack = SCROLLBACK_FOOTER;
            mScroller.startScroll(0, bottomMargin, 0, -bottomMargin,
                    SCROLL_DURATION);
            invalidate();
        }
    }

    private void startLoadMore() {
        mPullLoading = true;
        mIsPullLoadCompleted = false;
        if (mFooterView != null) {
            mFooterView.setState(UIListViewFooter.STATE_LOADING);
        }
        if (mListViewListener != null) {
            mListViewListener.onLoadMore();
        }
    }

    private int MAX_Y = 5;
    private int MAX_X = 3;
    private float mDownX;
    private float mDownY;
    private static int STATE_REFRESH = 1;
    private static int STATE_CEHUA = 2;

    /**
     * 禁止侧滑模式
     */
    public static int MOD_FORBID = 0;
    /**
     * 从左向右滑出菜单模式,该版本暂不支持
     */
    @Deprecated
    public static int MOD_LEFT = 1;
    /**
     * 从右向左滑出菜单模式
     */
    public static int MOD_RIGHT = 2;
    /**
     * 左右均可以滑出菜单模式
     */
    public static int MOD_BOTH = 3;
    /**
     * 当前的模式
     */
    private int mode = MOD_FORBID;
    /**
     * 左侧菜单的长度
     */
    private int leftLength = 0;
    /**
     * 右侧菜单的长度
     */
    private int rightLength = 0;
    /**
     * 当前滑动的ListView　position
     */
    private int slidePosition;
    /**
     * 手指按下X的坐标
     */
    private int downY;
    /**
     * 手指按下Y的坐标
     */
    private int downX;
    /**
     * ListView的item
     */
    private View itemView;
    /**
     * 滑动类
     */
    private Scroller scroller;
    /**
     * 认为是用户滑动的最小距离
     */
    private int mTouchSlop;

    /**
     * 判断是否可以侧向滑动
     */
    private boolean canMove = false;
    /**
     * 标示是否完成侧滑
     */
    private boolean isSlided = false;
    /**
     * 右侧拉出的菜单
     */
    public View rightView;
    /**
     * 左侧滑出的布局
     */
    @Deprecated
    private View leftView;
    int state = 0;
    int rightViewOffset = 0;
    View.OnTouchListener onTouchListener;


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (onTouchListener != null) {
            onTouchListener.onTouch(null, ev);
        }
        if (mLastY == -1) {
            mLastY = ev.getRawY();
        }
        final int action = ev.getAction();
        int lastX = (int) ev.getX();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastY = ev.getRawY();
                mDownX = ev.getX();
                mDownY = ev.getY();
                //-----------
                if (isSlided) {
                    scrollBack();
                    hideRightView();
                    return false;
                }
                // 假如scroller滚动还没有结束，我们直接返回
                if (!mScroller.isFinished()) {
                    return false;
                }
                slidePosition = pointToPosition((int) mDownX, (int) mDownY);
                // 无效的position, 不做任何处理
                if (slidePosition == AdapterView.INVALID_POSITION) {
                    return super.onTouchEvent(ev);
                }
                // 获取我们点击的item view
                itemView = getChildAt(slidePosition - getFirstVisiblePosition());

                //默认规则：id=llayout_right代表右侧布局的id
                rightView = itemView.findViewById(R.id.llayout_right);
                if (rightView == null) {
                    LogUtil.w("the itemview has no rightview in listview layout,please check its resource id-(请检查你id命名是否为llayout_right)");
                    return super.onTouchEvent(ev);
//				throw new RuntimeException("the itemview has no rightview in listview layout,please check its resource id-(请检查你id命名是否为llayout_right)");
                }
                if (this.mode == MOD_BOTH) {
                    this.leftLength = -itemView.getPaddingLeft();
                    this.rightLength = -rightView.getPaddingRight();
                } else if (this.mode == MOD_LEFT) {
                    this.leftLength = -itemView.getPaddingLeft();
                } else if (this.mode == MOD_RIGHT) {
                    this.rightLength = -rightView.getPaddingRight();
                    Integer tagValue = null;
                    //有些手机比较奇葩，拿不到padding的值
                    if (rightViewOffset == 0) {
                        String tag = (String) rightView.getTag();
                        if (tag != null) {
                            tagValue = Integer.parseInt(tag);
                            rightViewOffset = DensityUtil.dip2px(context, tagValue);
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                final float deltaY = ev.getRawY() - mLastY;
                float dy = Math.abs((ev.getY() - mDownY));
                float dx = Math.abs((ev.getX() - mDownX));
                mLastY = ev.getRawY();
//                LogUtil.d("moveing--------dy=" + dy + ",dx=" + dx);
                if (dy > dx) {
                    isXmoving = false;
                    if(state==STATE_CEHUA&&canMove){
                        break;
                    }
                    scrollBack();
                    state = STATE_REFRESH;
                    if (getFirstVisiblePosition() == 0 && (mHeaderView.getVisiableHeight() > 0 || deltaY > 0)) {
                        // the first item is showing, header has shown or pull down.
                        if (enableHeader) {
                            mScrollBack = 0;
                            updateHeaderHeight(deltaY / OFFSET_RADIO);
                            invokeOnScrolling();
                        }
                    } else if (getLastVisiblePosition() == mTotalItemCount - 1 && ((mFooterView != null && mFooterView.getBottomMargin() > 0) || deltaY < 0)) {
                        // last item, already pulled up or want to pull up.
                        if (enableFooter && enableFooter_AutoLoad) {
                            updateFooterHeight(-deltaY / OFFSET_RADIO);
                        }
                    }else {
                    }
                } else if (rightView != null) {
                    state = STATE_CEHUA;
//                    LogUtil.i("正在侧滑。。。");
                    isXmoving = false;
                    if (!canMove
                            && slidePosition != AdapterView.INVALID_POSITION
                            && Math.abs(ev.getX() - mDownX) > mTouchSlop) {
                        int offsetX = (int) mDownX - lastX;
                        if (offsetX > 0 && (this.mode == MOD_BOTH || this.mode == MOD_RIGHT)) {
                    /*从右向左滑*/
                            canMove = true;
                            rightView.setVisibility(VISIBLE);
                        } else if (offsetX < 0 && (this.mode == MOD_BOTH || this.mode == MOD_LEFT)) {
                    /*从左向右滑*/
                            canMove = true;
                            rightView.setVisibility(VISIBLE);
                        } else {
                            canMove = false;
                            rightView.setVisibility(GONE);
                        }
				/*此段代码是为了避免我们在侧向滑动时同时出发ListView的OnItemClickListener时间*/
                        MotionEvent cancelEvent = MotionEvent.obtain(ev);
                        cancelEvent
                                .setAction(MotionEvent.ACTION_CANCEL
                                        | (ev.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                        onTouchEvent(cancelEvent);
                    }
                    if (canMove) {
				/*设置此属性，可以在侧向滑动时，保持ListView不会上下滚动*/
                        requestDisallowInterceptTouchEvent(true);

                        // 手指拖动itemView滚动, deltaX大于0向左滚动，小于0向右滚
                        int deltaX = (int) mDownX - lastX;
                        if (deltaX < 0 && (this.mode == MOD_BOTH || this.mode == MOD_LEFT)) {
					/*向右滑*/
                            itemView.scrollTo(deltaX, 0);
                        } else if (deltaX > 0 && (this.mode == MOD_BOTH || this.mode == MOD_RIGHT)) {
					/*向左滑*/
                            rightView.scrollTo(deltaX, 0);
                        } else {
                            itemView.scrollTo(0, 0);
                        }
                        return true; // 拖动的时候ListView不滚动
                    }
                }else {
                    //非侧滑按钮的情况下
                    requestDisallowInterceptTouchEvent(true);
                    int deltaX = (int) mDownX - lastX;
                    if (deltaX < 0 ) {
					/*向右滑*/
//                        LogUtil.i("正在滑动中...向右滑");
                        isXmoving = true;
//                        return false;
                    } else if (deltaX > 0) {
					//向左滑
//                        LogUtil.i("正在滑动中...向左滑");
                        isXmoving = false;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (state == STATE_CEHUA) {
//                    LogUtil.i("抬起->正在侧滑...canMove="+canMove);
                    if (canMove&&rightView!=null) {
                        canMove = false;
                        scrollByDistanceX();
                    }else {
                    }
                } else {
                    mLastY = -1; // reset
                    if (getFirstVisiblePosition() == 0) {
                        // invoke refresh
                        if (enableHeader && mEnablePullRefresh && mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
                            mPullRefreshing = true;
                            mHeaderView.setState(UIListViewHeader.STATE_REFRESHING);
                            if (mListViewListener != null) {
                                mListViewListener.onRefresh();
                            }
                        }
                        if (enableHeader) {
                            resetHeaderHeight();
                        }
                    }
                    if (getLastVisiblePosition() == mTotalItemCount - 1) {
                        // invoke load more.
//                        if ((enableFooter && mFooterView != null) && (enableFooter_AutoLoad || mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA)) {
//                            startLoadMore();
//                            resetFooterHeight();
//                        }
                        if (enableFooter && !enableFooter_AutoLoad) {
                            resetFooterHeight();
                        }
                    }
//                    LogUtil.d("----isXmoving = "+isXmoving);
//                    if(isXmoving){
//                        return false;
//                    }else {
//                        return true;
//                    }
                }
                break;
        }
        return super.onTouchEvent(ev);
    }



    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            if (state == STATE_CEHUA && rightView != null) {
                // 让ListView item根据当前的滚动偏移量进行滚动
                rightView.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
                postInvalidate();
            } else if (state == STATE_REFRESH) {
                if (mScrollBack == SCROLLBACK_HEADER) {
                    //TODO 更新复位时的HeaderView的高度
                    int curY = mScroller.getCurrY();
//                    LogUtil.i("------CurrY="+curY+",%"+accuracy(curY,mHeaderViewHeight,0));
                    mHeaderView.setVisiableHeight(curY);
                } else {
                    if (mFooterView != null) {
                        mFooterView.setBottomMargin(mScroller.getCurrY());
                    }

                }
                postInvalidate();
                invokeOnScrolling();
            }
        }
        super.computeScroll();
    }

    private void hideRightView() {
        if (rightViewOffset != 0 && rightView != null && rightView.getVisibility() != GONE) {
//            LogUtil.d("----rightView.getTranslationX()=" + rightView.getTranslationX() + "X=" + rightView.getX());
            final ObjectAnimator anim = ObjectAnimator.ofFloat(rightView, "translationX", 0, rightViewOffset);
            anim.setDuration(100);
            anim.setInterpolator(new DecelerateInterpolator());
            anim.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animator) {
                }

                @Override
                public void onAnimationEnd(Animator animator) {
//                    LogUtil.d("----rightView.getTranslationX()=" + rightView.getTranslationX() + "X=" + rightView.getX());
                    rightView.setVisibility(GONE);
                    anim.reverse();
                    isSlided = false;
                }

                @Override
                public void onAnimationCancel(Animator animator) {
                }

                @Override
                public void onAnimationRepeat(Animator animator) {
                }
            });
            anim.start();
        }
    }

    public void initSlideMode(int mode) {
        if (mode == MOD_LEFT) {
            Log.w("warn", "暂不支持左侧菜单");
            this.mode = MOD_FORBID;
        } else {
            this.mode = mode;
        }
    }

    @Override
    public void setOnScrollListener(OnScrollListener l) {
        mScrollListener = l;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (mScrollListener != null) {
            mScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        // send to user's listener
        if (getLastVisiblePosition() == mTotalItemCount - 3) {
            // invoke load more.
            if ((enableFooter && mFooterView != null) && (enableFooter_AutoLoad || mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA)) {
                startLoadMore();
                resetFooterHeight();
            }
        }
        mTotalItemCount = totalItemCount;
        if (mScrollListener != null) {
            mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
                    totalItemCount);
        }
    }

    public void setCListViewListener(ICListViewListener l) {
        mListViewListener = l;
    }

    /**
     * you can listen ListView.OnScrollListener or this one. it will invoke
     * onXScrolling when header/footer scroll back.
     */
    public interface OnCScrollListener extends OnScrollListener {
        public void onXScrolling(View view);
    }

    public interface ICListViewListener {

        public void onRefresh();

        public void onLoadMore();
    }


    /**
     * 根据手指滚动itemView的距离来判断是滚动到开始位置还是向左或者向右滚动
     */
    private void scrollByDistanceX() {
		/*当前模式不允许滑动，则直接返回*/
        if (this.mode == MOD_FORBID) {
            return;
        }
        if (rightView.getScrollX() > 0 && (this.mode == MOD_BOTH || this.mode == MOD_RIGHT)) {
			/*从右向左滑*/
            if (rightView.getScrollX() >= rightLength / 2) {
                scrollLeft();
            } else {
                // 滚回到原始位置
                scrollBack();
            }
        } else if (itemView.getScrollX() < 0 && (this.mode == MOD_BOTH || this.mode == MOD_LEFT)) {
			/*从左向右滑*/
            if (itemView.getScrollX() <= -leftLength / 2) {
                scrollRight();
            } else {
                // 滚回到原始位置
                scrollBack();
            }
        } else {
            // 滚回到原始位置
            scrollBack();
        }

    }

    /**
     * 往右滑动，getScrollX()返回的是左边缘的距离，就是以View左边缘为原点到开始滑动的距离，所以向右边滑动为负值
     */
    private void scrollRight() {
        isSlided = true;
        final int delta = (leftLength + rightView.getScrollX());
        // 调用startScroll方法来设置一些滚动的参数，我们在computeScroll()方法中调用scrollTo来滚动item
        mScroller.startScroll(rightView.getScrollX(), 0, -delta, 0,
                Math.abs(delta));
        postInvalidate(); // 刷新itemView
    }

    /**
     * 向左滑动，根据上面我们知道向左滑动为正值
     */
    private void scrollLeft() {
        isSlided = true;
        final int delta = (rightLength - rightView.getScrollX());
        // 调用startScroll方法来设置一些滚动的参数，我们在computeScroll()方法中调用scrollTo来滚动item
        mScroller.startScroll(rightView.getScrollX(), 0, delta, 0,
                Math.abs(delta));
        postInvalidate(); // 刷新itemView
    }

    /**
     * 滑动会原来的位置
     */
    private void scrollBack() {
        if (rightView != null) {
            isSlided = false;
            mScroller.startScroll(rightView.getScrollX(), 0, -rightView.getScrollX(),
                    0, Math.abs(rightView.getScrollX()));
            postInvalidate(); // 刷新itemView
        }
    }

    public void hideMenu() {
        if (rightView != null)
            scrollBack();
    }

    /**
     * 提供给外部调用，用以将侧滑出来的滑回去
     */
    public void slideBack() {
        this.scrollBack();
    }

    public View getRightView() {
        return rightView;
    }

    public static int accuracy(double num, double total, int scale){
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        //可以设置精确几位小数
        df.setMaximumFractionDigits(scale);
        //模式 例如四舍五入
        df.setRoundingMode(RoundingMode.HALF_UP);
        if(num>=total){
            return 100;
        }
        double accuracy_num = num / total * 100;
        return (int) accuracy_num;
    }

    public void setonTouchListener(OnTouchListener onTouchListener) {
        this.onTouchListener = onTouchListener;
    }
}
